package com.pdlocation.viewmodel;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;

import com.pdlocation.model.LocationPoint;
import com.pdlocation.repository.DataRepository;
import com.pdlocation.service.TrackingService;


//视图模
public class LocationViewModel extends ViewModel {
    private final DataRepository repository;

    public LocationViewModel() {
        repository = DataRepository.getInstance();
    }

    // 暴露LiveData给页面
    public LiveData<LocationPoint> getData() {
        return repository.getDataLiveData();
    }

    // 启动Service的方法
    public void startTrackingService(Context context) {
        Intent serviceIntent = new Intent(context, TrackingService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(serviceIntent);
        } else {
            context.startService(serviceIntent);
        }
    }

    // 停止Service的方法
    public void stopTrackingService(Context context) {
        Intent serviceIntent = new Intent(context, TrackingService.class);
        context.stopService(serviceIntent);
    }

    //判断服务是否还在运行
    public boolean isTrackingServiceRunning(Class<?> serviceClass, Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
}